import { Component, OnInit } from '@angular/core';

import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';

import { appHardcoreAreaService } from './app-hardcore-area.service';
import {PermissionService} from '../../../service/permission.service';
import { CommonService } from 'src/app/services-common/common.service';

@Component({
  selector: 'app-hardcore-area',
  templateUrl: './app-hardcore-area.component.html',
  styleUrls: ['./app-hardcore-area.component.scss'],
  providers: [DatePipe]
})
export class AppHardcoreAreaComponent implements OnInit {

  /**
   * 查询参数格式
   */
  queryForm: any = {
    // 状态：0 无效  1 启用
    status: '',
    // 当前页码
    pageNum: 1,
    // 分页大小
    pageSize: 10,
    // 平台 默认移动端 平台：1 移动B端 2 移动C端 3 PC端B端  4 PC端C端 5爱乐物B端 6爱乐物C端
    platform: '1'
  }

  // 新增弹窗对象
  modalForm: any = {
    // 导航栏名称
    ntName: '',
    // 日常图标
    ntPicUrl: '',
    // 日常角标
    cornerMarker: '',
    // 活动图标
    activityPicture: '',
    // 跳转方式
    type: '1',
    // 跳转链接
    ntUrl: '',
    // 参数
    params: '',
    // 状态 0：无效，1：有效
    status: 1,
    // 备注
    bak: ''
  }
  // 设置
  popoverForm: any = {
    // 0 隐藏  1显示
    kingKongSetting: 1
  }
  // 上传列表集合
  fileList: any = []
  /**
   * 表单load加载
   */
  tableLoading: any = false;
  // 列表数据
  tableData: any = {
    // 数据列表集合
    records: [],
    // 总条数
    total: 0,
    // 当前页面
    pages: 0,
    // 每页的条数
    size: 0,
  }
  isModalShow: boolean = false
  // 上传等待动画
  modalUploadLoading: boolean = false

  // 控制金刚区弹窗
  visible: boolean = false;
  /**
   * 全局 loading
   */
  messageId: any = null;

  // 防止重复上传
  forbidUpload: boolean = false

  // 定时器
  time: any = null

  // 缓存
  cacheData: any = {
    // 列表id 编辑的时候要用到
    id: '',
    // 日常图标
    ntPicUrl: '',
    // 日常角标
    cornerMarker: '',
    // 活动图标
    activityPicture: ''
  }

  // 类型 1.链接 2.商品 3.搜索词 4.第三级分类
  // typeSet: any = { 1: '链接', 2: '指定商品', 3: '搜索词', 4: '第三级分类' }
  // 1.商品id 2.链接 3.搜索词 4.分类（2021/7/28）
  typeSet: any = { 1: '商品id', 2: '链接', 3: '搜索词', 4: '分类' }

  // topTabs切换 平台：1 移动B端 2 移动C端 3 PC端B端  4 PC端C端 5爱乐物B端 6爱乐物C端 7小程序B端 8小程序C端
  tabLists: any = [{
    value: '1',
    label: '移动B端'
  }, {
    value: '2',
    label: '移动C端'
  }, {
    value: '3',
    label: 'PC端B端'
  }, {
    value: '4',
    label: 'PC端C端'
  }, {
    value: '5',
    label: '爱乐物B端'
  }, {
    value: '6',
    label: '爱乐物C端'
  }, {
    value: '7',
    label: '小程序B端'
  }, {
    value: '8',
    label: '小程序C端'
  }];
  selectIndex: any = 0;
  tablePages: any = 0;

  // 活动时间设置
  activityDates: any = [];

  mappingOptions: any = [];

  constructor(
    private appHardcoreAreaService: appHardcoreAreaService,
    private message: NzMessageService,
    public permission: PermissionService,
    private commonService: CommonService,
    private datePipe: DatePipe
  ) { }

  async ngOnInit() {
    await this.getMappingData()
    this.httpList()
  }

  // 获取映射list
  async getMappingData() {
    let params = {
      page: 1,
      pageSize: 10000
    }
    const res: any = await this.commonService.getMappingData(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      this.mappingOptions = records || []
    }
  }

  // Top切换
  changeTabs(e: any) {
    this.queryForm.platform = e;
    this.activityDates = [];
    
    this.httpList()
  }

  // 查询列表
  onQuery() {
    this.queryForm.pageNum = 1
    this.httpList()
  }
  // 列表删除 status 2
  onTableDelete(item: any) {
    const { id } = item
    this.httpPostNavigationBar(`${id}/2`, {})
  }
  // 列表禁用 status 0
  onTableDisable(item: any) {
    const { id } = item
    this.httpPostNavigationBar(`${id}/0`, {})
  }
  // 列表开启 status 1
  onTableEnable(item: any) {
    const { id } = item
    this.httpPostNavigationBar(`${id}/1`, {})
  }
  // 上移和下移
  onTableMove(item: any, type: string) {
    const { id } = item
    this.httpPutNavigationBar(`${type}/${id}`, {})
  }
  // 编辑
  onTableEdit(item: any) {
    const { id, ntName, ntPicUrl, cornerMarker, activityPicture, type, ntUrl, params, status, bak } = item
    this.modalForm = { ntName, ntPicUrl, cornerMarker, activityPicture, type: `${type}`, ntUrl, params, status, bak }
    this.cacheData = { ntPicUrl, cornerMarker, activityPicture, id }
    this.isModalShow = true
  }
  /**
   * 页码改变
   * @param index 页码数
   */
  onPageIndexChange(index: Number) {
    this.queryForm.pageNum = index;
    this.httpList()
  }
  /**
   * 每页条数改变的回调
   * @param index 页码数
   */
  onPageSizeChange(index: Number) {
    this.queryForm.pageSize = index;
    this.httpList()
  }

  // 金刚区 新增
  onOpenModalAdd() {
    this.cacheData.id = '' // id 传空为新增
    this.modalForm = { status: 1 }
    this.cacheData = {}
    this.isModalShow = true
  }
  // 金刚区 显示弹窗
  onHardcore() {
    this.visible = true
  }

  // 金刚区 确定
  async onSurePopover() {
    const { kingKongSetting } = this.popoverForm
    try {
      const { message }: any = await this.appHardcoreAreaService.httpSetting(kingKongSetting, {})
      this.visible = false
      message && this.message.success(message)
      this.httpList() // 刷新列表
    } catch (error) {
    }
  }
  // 金刚区 确定
  onClosePopover() {
    this.visible = false
  }
  // 关闭新增弹窗
  onModalClose() {
    this.isModalShow = false
  }
  // 上传图标和角标的按钮
  onModalPreview(ev: any, key: string) {
    const { thumbUrl, originFileObj } = ev?.file
    // this.cacheData[key] = thumbUrl
    this.httpUpload(originFileObj, key)
  }
  // 删除上传图片
  onDelectImg() {
    this.cacheData.cornerMarker = ''
    this.modalForm.cornerMarker = ''
  }
  // 指定商品
  oninputLink(ev: any) {
    const { type } = this.modalForm
    if (type == 1) {
      this.time = setTimeout(() => {
        this.modalForm.ntUrl = ev.target.value.replace(/[^\d]/g, '')
        clearTimeout(this.time)
      }, 300);

    }
  }
  // 金刚区 新增 确定提价数据
  async onConfirm() {
    const { ntName, ntPicUrl, type, ntUrl, status } = this.modalForm
    const { id } = this.cacheData
    if (!ntName) {
      this.message.warning('请输入名称')
      return
    }
    if (!ntPicUrl) {
      this.message.warning('请选择日常图标')
      return
    }
    // if (!type) {
    //   this.message.warning('请选择跳转方式')
    //   return
    // }
    // if (!ntUrl) {
    //   this.message.warning('请输入链接地址')
    //   return
    // }
    if (![0, 1].includes(status)) {
      this.message.warning('请选择状态')
      return
    }
    // console.log('upload imgs', this.modalForm);
    // return
    const formData = new FormData()
    for (const iterator in this.modalForm) {
      if (this.modalForm[iterator] == null || this.modalForm[iterator] == 'null' || this.modalForm[iterator] == undefined) {
        this.modalForm[iterator] = '';
      }
      formData.append(iterator, this.modalForm[iterator])
    }
    let isSuccess = null

    formData.append('platform', this.queryForm.platform) // 添加平台
    if (id) {
      // 编辑
      isSuccess = await this.httpPutNavigationBar(id, formData)
    } else {
      // 新增保存
      isSuccess = await this.httpPostNavigationBar('', formData)
    }
    if (isSuccess) {
      this.isModalShow = false // 关闭弹窗
    }

  }
  /**
   * 查询列表
   * @returns
   */
  async httpList() {
    this.createBasicMessage()
    try {
      const { data }: any = await this.appHardcoreAreaService.httpGetNavigationBar(this.queryForm)
      const { iPage, kingKongSetting } = data || {}
      if (iPage) {
        this.tableData = iPage
        this.popoverForm.kingKongSetting = kingKongSetting
        this.tablePages = iPage.pages || 0;

        this.activityDates = data.beginTime ? [data.beginTime, data.endTime] : [];
      }
      this.removeBasicMessage()
    } catch (error) {
      this.removeBasicMessage()
      this.tablePages = 0;
    }
  }
  /**
   * 图片 上传
   * @returns
  */
  async httpUpload(originFileObj: any, key: string) {
    if (!originFileObj || this.forbidUpload) { // 禁止 重复上传
      return
    }
    this.forbidUpload = true
    try {
      const { data }: any = await this.appHardcoreAreaService.httpPostFile(originFileObj)
      this.modalForm[key] = data
      this.forbidUpload = false
      data && this.message.success('图片上传成功')

      this.cacheData[key] = data
    } catch (error) {
      this.forbidUpload = false
      this.message.warning('图片上传失败，请重新选取上传')

      this.cacheData[key] = ''
    }
  }
  /**
   * 提交新增弹窗的数据
   * @returns
  */
  async httpPostNavigationBar(query: any, params: any) {
    if (!params) {
      return
    }
    try {
      const { message, code }: any = await this.appHardcoreAreaService.httpPostNavigationBar(query, params)
      code == 0 && message && this.message.success(message)
      code != 0 && message && this.message.warning(message)
      if (code === 0) {
        this.time = setTimeout(() => {
          this.queryForm.pageNum = 1
          this.httpList() // 成功刷新列表
          clearTimeout(this.time)
        }, 500);
      } else {
        this.message.error(message);
      }
      return message == 'success'
    } catch (error) {
      // console.log(error, 'error')
      return false;
    }
  }
  /**
  * 提交新增弹窗的数据
  * @returns
 */
  async httpPutNavigationBar(query: any, params: any) {
    if (!params) {
      return
    }
    try {
      const { message, code }: any = await this.appHardcoreAreaService.httpPutNavigationBar(query, params)
      code == 0 && message && this.message.success(message)
      code != 0 && message && this.message.warning(message)
      if (message == 'success') {
        this.time = setTimeout(() => {
          this.httpList() // 成功刷新列表
          clearTimeout(this.time)
        }, 500);
      }
      return message == 'success'
    } catch (error) {
      console.log(error, 'error')
      return false;

    }
  }

  // disabled move
  disabledMoveBtn(index?: number): boolean {
    if ((this.queryForm.pageNum == this.tablePages) && index == this.tableData?.records.length - 1) {
      return true
    } else {
      return false
    }
  }

  // 活动时间change
  async onTimeChange(result: Date[]) {
    let params = {
      platform: this.queryForm.platform,
      beginTime: result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss') : '',
      endTime: result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss') : ''
    }
    
    this.createBasicMessage();
    const res: any = await this.appHardcoreAreaService.updateTimeData(params);
    this.removeBasicMessage();
    if (res.code == 0) {
      this.message.success('操作成功');
      this.httpList();
    } else {
      this.message.error(res.message || '操作失败');
    }
  }

  // table状态字段code转换成中文
  status_to_text(val: any) {
    const text: any = { 0: '禁用', 1: '启用' }
    return text[val] || '-'
  }
  /**
   * 开启loading
   */
  createBasicMessage(): void {
    this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
  }
  /**
   * 移除loading
   */
  removeBasicMessage() {
    this.message.remove(this.messageId);
    this.messageId = null;
  }
  /**
  * 全局展示操作反馈信息
  * @param type 其他提示类型 success:成功 error:失败 warning:警告
  */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }

  // 映射链接备注Filter
  remarkFilter(key: any) {
    let tempObj: any = this.mappingOptions.find((item: any) => {
      return item?.key === key
    })
    return tempObj?.remarks || '';
  }
}
